package model;

import java.util.HashMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

class InstructionMemory extends FunctionalUnit {
	
	private HashMap<Integer, String> content = new HashMap<Integer, String>();
	
	private int address;
	
	public InstructionMemory(Pipe sourcePipe, Pipe destinationPipe) {
		super(sourcePipe, destinationPipe);
	}
	
	public void setData (int address, String data) {
		content.put(address,data);
	}
	
	public String getData(int address) {
		return content.get(address);
	}

	public void execute1() {
		address = getPipeData("ADDRESS");
		Facade.getInstance().move(UnitEnum.ProgramCounter, UnitEnum.InstructionMemory, address);		
	}
	
	public void execute2() {
		String instruction = content.get(address);
		Pattern p =Pattern.compile("([0-9]+)");
		Matcher m = p.matcher(instruction);
		m.find(); //tratare erori
		setPipeData("BASE", Integer.parseInt( m.group() ));
		Facade.getInstance().move(UnitEnum.InstructionMemory, UnitEnum.Pipe1, 1, Integer.parseInt(m.group()) );
		m.find(); //tratare erori
		setPipeData("OFFSET", Integer.parseInt( m.group() ));
		Facade.getInstance().move(UnitEnum.InstructionMemory, UnitEnum.Pipe1, 2, Integer.parseInt(m.group()) );
		m.find(); //tratare erori
		setPipeData("DESTREG", Integer.parseInt( m.group() ));
		Facade.getInstance().move(UnitEnum.InstructionMemory, UnitEnum.Pipe1, 3, Integer.parseInt(m.group()) );
	}

}
